/*
 * File:    sys_cfg_tok.c 
 * Author:  Yin Lijun <yinlijun2004@gmail.com>
 * Brief:   system config parser utility.
 *
 * Copyright (c) 2011 - 2012  Yin Lijun <yinlijun2004@gmail.com>
 *
 * Licensed under the Academic Free License version 2.1
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/*
 * History:
 * ================================================================
 * 2013-11-15 Yin Lijun <yinlijun2004@gmail.com> created
 *
 */ 

#include "sys_cfg_tok.h"
#include <string.h>                                                           
#include <ctype.h>                                                            
#include <stdlib.h>                                                           

static void skipNextComma(char **p_cur)
{
    if (*p_cur == NULL) return;

    while (**p_cur != '\0' && **p_cur != ',')
    {
        (*p_cur)++;
    }

    if (**p_cur == ',')
    {
        (*p_cur)++;
    }
}


static void skipWhiteSpace(char **p_cur)
{
    if (*p_cur == NULL) return;

    while (**p_cur != '\0' && isspace(**p_cur)) 
    {
        (*p_cur)++;
    }
}

static char * nextTok(char **p_cur)
{
    char *ret = NULL;

    skipWhiteSpace(p_cur);
    if (*p_cur == NULL)
    {
        ret = NULL;
    }
    else if (**p_cur == '"')
    {
        (*p_cur)++;
        ret = strsep(p_cur, "\"");
        skipNextComma(p_cur);
    }
    else
    {
        ret = strsep(p_cur, ",");
    }

    return ret;
}

int cfg_tok_nextstr(char **p_cur, char **p_out)
{
    if (*p_cur == NULL)
    {
        return -1;
    }

    *p_out = nextTok(p_cur);

    return 0;
}
